package com.onetech.adrewards.free.dialogs;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Build;
import android.os.Bundle;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
import com.onetech.adrewards.free.config.AppConfig;
import com.onetech.adrewards.free.config.AppConfig.URLRequestApi;
import com.onetech.adrewards.free.http.APIRequestResult;
import com.onetech.adrewards.free.http.ZuZuHttpRequest;
import com.onetech.adrewards.free.objects.FeedBackDTO;
import com.onetech.adrewards.free.utils.AdrewadsUtils;
import com.onetech.adrewards.free.R;
import com.zuzu.dialogs.BaseDialog;

public class FeedbackDialog extends BaseDialog {
	private View mSubmitBtn=null;
	private SendFeedBack mSendFeedBack=null;
	private FeedBackDTO mData=null;
	private EditText name=null;
	private EditText email=null;
	private EditText type=null;
	private EditText contents=null;
	private ImageView mMenuPopup=null;
	private AlertDialog mGenderSelectDialog=null;
	
	private Tracker mTracker;
	private Context mContext=null;
	public FeedbackDialog(Context context){
		super(context, context.getString(R.string.feedback_title),TYPE_NO_BUTTON, R.layout.feedback_layout);
		mContext=context;
		initView();
		initListener();
	}
	private void initView(){
		name=(EditText)findViewById(R.id.fb_name);
		email=(EditText)findViewById(R.id.fb_email);
		type=(EditText)findViewById(R.id.fb_type);
		contents=(EditText)findViewById(R.id.fb_contents);
		mSubmitBtn=(LinearLayout)findViewById(R.id.submitBtn);
		mMenuPopup=(ImageView)findViewById(R.id.menu_popup);
	}
	private void initListener(){
		mSubmitBtn.setOnClickListener(this);
		mMenuPopup.setOnClickListener(this);
		type.setKeyListener(null);
	}
	@Override
	public void onClick(View v) {	
		switch (v.getId()) {
		case R.id.submitBtn:
			sendFeedBack();			
			break;
		case R.id.menu_popup:
			selectFeedbackType();
			break;
		default:
			super.onClick(v);
			break;
		}
	}
	private void selectFeedbackType(){
		final String[] items = getContext().getResources().getStringArray(
				R.array.feedback_names);
		ContextThemeWrapper themedContext;
		if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
		    themedContext = new ContextThemeWrapper( getContext(), android.R.style.Theme_Holo_Light_Dialog_NoActionBar );
		}
		else {
		    themedContext = new ContextThemeWrapper( getContext(), android.R.style.Theme_Light_NoTitleBar );
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(themedContext);
		
		builder.setTitle(getContext().getString(
				R.string.dialog_feedback_type_title));
		builder.setSingleChoiceItems(items, 0,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						try {
							type.setText(items[item]);
						} catch (Exception e) {
							return;
						}
						mGenderSelectDialog.dismiss();
					}
				});
		mGenderSelectDialog = builder.create();
		mGenderSelectDialog.show();
	}
	private void sendFeedBack(){
		mData=new FeedBackDTO();
		mData.setName(name.getText().toString().trim());
		mData.setEmail(email.getText().toString().trim());
		mData.setType(type.getText().toString().trim());
		mData.setContents(contents.getText().toString().trim());
		if(mData.getName().length()<1 || mData.getEmail().length()<1 || mData.getType().length()<1 || mData.getContents().length()<1){
			Toast.makeText(getContext(), getContext().getString(R.string.input_empty_message), Toast.LENGTH_LONG).show();
			//AdrewadsUtils.showInfoDialog(getContext(),"", getContext().getString(R.string.input_empty_message));
			return;
		}
		if(!AdrewadsUtils.validateEmail(mData.getEmail())){
			Toast.makeText(getContext(), getContext().getString(R.string.input_email_invalid_message), Toast.LENGTH_LONG).show();
			//AdrewadsUtils.showInfoDialog(getContext(),"", getContext().getString(R.string.input_email_invalid_message));			
			return;
		}
		if(mSendFeedBack==null || mSendFeedBack.getStatus()==Status.FINISHED){
			mSendFeedBack=new SendFeedBack();
			mSendFeedBack.execute();
		}
	}
	
	private class SendFeedBack extends AsyncTask<Void, Void, APIRequestResult>{
		@Override
		protected APIRequestResult doInBackground(Void... params) {
			if(mData==null){
				return null;
			}
			AdrewadsUtils.checkUId();
			Bundle mParams=new Bundle();
			mParams.putString("contents", mData.getContents());
			mParams.putString("email", mData.getEmail());
			mParams.putString("name", mData.getName());
			mParams.putString("type", mData.getType());
			mParams.putString("mem_id", AppConfig.uId);
			
			return ZuZuHttpRequest.getInstance().postDataToServer(URLRequestApi.POST_FEEDBACK_USER, mParams);
		}
		@Override
		protected void onPostExecute(APIRequestResult data) {
			super.onPostExecute(data);
			if(data==null){
				return;
			}
			try {
				if (data.error_code.equals("0") && data.data != null && !data.data.equals("")) {
					JSONObject jsonObject=(JSONObject)data.data;								
					JSONObject jb=jsonObject.getJSONObject("result");
					String result=jb.getString("status");
					if(result.trim().equals("ok")){
						//Toast.makeText(getContext(), getContext().getString(R.string.feedback_success_message), Toast.LENGTH_LONG).show();
						AdrewadsUtils.showInfoDialog(getContext(),"", getContext().getString(R.string.feedback_success_message));
						dismiss();
					}else{
						//Toast.makeText(getContext(), getContext().getString(R.string.feedback_failed_message), Toast.LENGTH_LONG).show();
						AdrewadsUtils.showInfoDialog(getContext(),"", getContext().getString(R.string.feedback_failed_message));
					}
				}
			} catch (Exception e) {
				Toast.makeText(getContext(), getContext().getString(R.string.feedback_failed_message), Toast.LENGTH_LONG).show();
			}
		}
	}
	@Override
    public void onStart() {
        super.onStart();
        try {
            mTracker.set(Fields.SCREEN_NAME, mContext.getString(R.string.FeedbackDialog));            
            mTracker.send(MapBuilder.createAppView().build());            
		} catch (Exception e) {
		}
    }
}
